<template>
  <div class="online_code">
    <header class="header">
      <div class="left_btn_group">
        <HPlainButton @click="createDialog = true">创建条码</HPlainButton>
        <HPlainButton @click="printTemp">打印模版</HPlainButton>
      </div>
      <div class="detail_info_container">
        <div class="detail_info">
          <el-select
            v-model="value1"
            :filter-method="remoteMethod"
            :loading="loading"
            remote-show-suffix
            placeholder="请选择条码"
            filterable
            clearable
            class="select_code"
            @change="changeSel"
          >
            <el-option
              v-for="(item, index) in options1"
              :key="index"
              :value="item.id"
              :label="item.name + '  ' + item.code"
            />
          </el-select>
          <el-select
            v-model="value2"
            placeholder="请选择产品"
            filterable
            clearable
            class="select_product"
            @change="changeSel2"
          >
            <el-option
              v-for="(item, index) in options2"
              :key="index"
              :value="item.id"
              :label="
                item.brand + ' ' + item.goodsModel + ' ' + item.goodsName + ' ' + item.goodsSpecName
              "
            />
          </el-select>
          <el-select
            v-model="value"
            class="select_template"
            :filter-method="nameMethod"
            :loading="loading2"
            remote-show-suffix
            placeholder="选择模版"
            size="large"
            filterable
            clearable
            @change="selectChange"
          >
            <el-option
              v-for="(item, index) in options3"
              :key="index"
              :value="item.id"
              :label="item.name"
              :disabled="item.status"
            />
          </el-select>
          <div class="text_print">
            <span class="spac text">
              共
              <span class="num">{{ total }}</span>
              条条码，
            </span>
            <span class="spac text">每页条码数</span>
            <el-input-number
              v-model.trim="input2"
              :controls="false"
              class="page_num each_page_code_num"
              @input="inputchange"
            />
            <span class="spac text">
              共
              <span class="num">{{ pages }}</span>
              页，
            </span>
            <span class="spac text">
              打印第
              <el-input-number
                v-model.trim="input"
                :controls="false"
                :max="pages"
                class="page_num total_page"
                @input="changeInputPages"
              />
              页
            </span>
            <span class="statistics text">
              统计( 单码打印数量: <span class="num">{{ codeNum }}</span> 单行排列数量:
              <span class="num">{{ rowQty }}</span> 打印总数量:
              <span class="num">{{ codeNum * input2 }}</span>
              )
            </span>
          </div>
        </div>
        <div class="btn_group">
          <HPlainButton @click="lookTemp">预览</HPlainButton>
          <HPlainButton @click="print2">打印</HPlainButton>
        </div>
      </div>
    </header>
    <div class="line"></div>

    <body
      v-loading="printDataing"
      class="app-container body"
      style="height: 100%"
      element-loading-text="加载中..."
    >
      <div class="header">
        <div class="left">
          <span>摘选10条数据预览 预览无误，点击右侧打印按钮执行打印(当前页面仅查看模版)</span>
        </div>
      </div>
      <!-- 预览 -->
      <div style="height: 100%; flex: 1; overflow: auto; background-color: #f1f1f1; padding: 12px">
        <div v-if="lookShow" class="bg_card">
          <templateMain :item-data="printList" />
        </div>
      </div>
      <!-- 打印 -->
      <div
        style="overflow: auto; display: none; height: 92%; background-color: #f1f1f1; padding: 12px"
      >
        <div v-if="printData" class="prin_card bg_card">
          <templateMain2 :item-data="printList" :print-data="printData" />
        </div>
      </div>
    </body>
    <!-- 创建条码弹窗 -->
    <CreateCodepopup v-model="createDialog" />
    <!-- 预览弹窗 -->
    <el-dialog v-model="lookShow2" title="预览" width="70%" top="8vh" class="lookshow2" draggable>
      <div style="overflow: auto; height: 70vh; background-color: #f1f1f1; padding: 14px">
        <div class="bg_card">
          <templateMain2 :item-data="printList" :print-data="printData" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, nextTick } from 'vue'
  import { useRouter } from 'vue-router'
  import templateMain from '@/views/code/online/module/templateMain.vue'
  import templateMain2 from '@/views/code/online/module/templateMaintwo.vue'
  import CreateCodepopup from '../../code/list/detail/components/createCodepopup/index.vue'
  import { ElMessage } from 'element-plus'
  import '@/utils/Print'
  import * as _ from 'lodash'
  import {
    codeBatchPageSelect,
    getPrintTemplateData,
    codeBatchGoodsPageSelect,
    printTemplateList,
    printTemplateGetDetail,
  } from '../../../api/code'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.snCode.codeingOnline,
  })

  const router = useRouter()
  const value = ref(null) //模版name搜索
  const input = ref(1)
  const input2 = ref(0)
  const loading2 = ref(false)
  const printList = ref(null)
  const printData = ref(null) //打印数据
  const total = ref(0) //共有数据
  const pages = ref(0) //共有页数
  const createDialog = ref(false)
  const options1 = ref(null)
  const options2 = ref(null)
  const options3 = ref(null)
  const printDataing = ref(null)
  const pageData = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const pageData2 = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const codeNum = ref(0)
  const rowQty = ref(0)
  const lookShow = ref(false) //查看模版
  const lookShow2 = ref(false) //预览弹窗
  const value1 = ref() //批次条码id
  const loading = ref(true)
  const indexSel = ref(0)
  const value2 = ref('') //产品id
  const digData = ref(null)
  const changeSel = (val) => {
    indexSel.value = val
    value2.value = null
    if (!val) {
      return
    }
    codeBatchGoodsPageSelect(pageData2, val).then((res) => {
      options2.value = res.data.data.rows
      total.value = 0
    })
  }
  // 产品选择
  const changeSel2 = (val) => {
    if (val) {
      options2.value.filter((o) => {
        if (o.id == val) {
          total.value = o.qty
          if (o.qty != 0) {
            if (total.value >= 10) {
              input2.value = 10
            } else {
              input2.value = total.value
            }
            pages.value = 1
            input.value = 1
          }
        }
      })
      value.value = null
    }
  }
  const remoteMethod = _.throttle((val: string) => {
    if (pageData.name !== val) {
      pageData.name = val
      getCodeBatchPageSelect()
    }
  }, 500)
  const getCodeBatchPageSelect = async () => {
    loading.value = true
    const res = await codeBatchPageSelect(pageData)
    loading.value = false
    options1.value = res.data.data.rows
  }

  const getPrintTemplateListParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })
  const inputMod = async () => {
    loading2.value = true
    const res = await printTemplateList(getPrintTemplateListParam.value)
    if (res.data.success) {
      options3.value = res.data.data.rows
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 5000,
        plain: true,
      })
    }
    loading2.value = false
  }
  const printTemp = () => {
    router.push({ path: '/code/printtemp' })
  }
  // 预览
  const lookTemp = async () => {
    if (!value2.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        duration: 5000,
        plain: true,
        message: '请先选择预览数据！',
      })
      return
    }
    if (!value.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        duration: 5000,
        plain: true,
        message: '请先选择打印模版！',
      })
      return
    }
    getpeinData(true)
  }
  // 获取打印数据
  const getpeinData = async (val) => {
    printData.value = null
    printDataing.value = true
    let data = {
      batchGoodsId: value2.value,
      batchId: value1.value,
      limit: input2.value,
      page: input.value,
      printTempLateId: value.value,
    }
    const res = await getPrintTemplateData(data)
    if (res.data.success) {
      printData.value = res.data.data.row
      lookShow2.value = val
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 5000,
        plain: true,
      })
    }
    printDataing.value = false
  }
  // 打印
  const print2 = async () => {
    if (!value2.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        duration: 5000,
        plain: true,
        message: '请先选择打印数据！',
      })
      return
    }
    if (!value.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        duration: 5000,
        plain: true,
        message: '请先选择打印模版！',
      })
      return
    }
    getpeinData(false)
    nextTick()
    Print('.prin_card', {
      onStart: function () {},
      onEnd: function () {},
    })
  }

  // 每页打印数
  const inputchange = (val) => {
    if (total.value < val) {
      ElMessage({
        type: 'warning',
        showClose: true,
        message: '最大数不能超过总数！',
        duration: 5000,
        plain: true,
      })
      input2.value = null
      nextTick(() => {
        input2.value = total.value
      })
      return
    }
    if (val <= 0) {
      nextTick(() => {
        input2.value = 1
        pages.value = 1
        input.value = 1
      })
      return
    }
    pages.value = Math.ceil(total.value / val) || 0
    if (input.value > pages.value) {
      input.value = pages.value
    }
  }
  const changeInputPages = (val) => {
    if (val <= 0) {
      nextTick(() => {
        pages.value = 1
        input.value = 1
      })
      return
    }
    if (val > pages.value) {
      nextTick(() => {
        input.value = pages.value
      })
    }
  }
  // 选择模版
  const selectChange = (val) => {
    getprinData(val)
  }
  // 获取打印模版数据
  const getprinData = (val) => {
    if (!val) return
    printTemplateGetDetail(val).then((res) => {
      if (res.data.success) {
        let tmp = res.data.data.row
        printList.value = JSON.parse(JSON.stringify(tmp))
        codeNum.value = printList.value.codeNum
        rowQty.value = printList.value.rowQty
        lookShow.value = true
      } else {
        ElMessage({
          type: 'error',
          showClose: true,
          message: res.data.message,
          duration: 5000,
          plain: true,
        })
      }
    })
  }
  // 模版名称搜索
  const nameMethod = _.throttle((val: string) => {
    if (!value1.value || !value2.value) {
      return
    }

    if (getPrintTemplateListParam.value.name !== val) {
      getPrintTemplateListParam.value.name = val
      inputMod()
    }
  }, 500)

  onMounted(() => {
    digData.value = JSON.parse(localStorage.getItem('digData'))
    getCodeBatchPageSelect()
    inputMod()
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
<style>
  @media print {
    @page {
      size: auto;
    }

    body,
    html {
      height: auto !important;
    }
  }
</style>
